package net.misp.beta.timerapp;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.ToggleButton;

public class MainActivity extends Activity implements OnCheckedChangeListener,
		OnItemSelectedListener {

	EditText mEdit;
	ToggleButton mToggle;
	int mCount;
	int mSet = 0;
	Button mButton;
	Spinner mSpinner;
	long mInterval = 30000;
	Timer mTimer;
	TimerTask mTimerTask;
	Handler mHandler;
	ProgressDialog mDialog = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {

		String[] interval = { "30秒", "1分", "1分30秒", "2分" };

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		mEdit = (EditText) findViewById(R.id.edittext1);
		mButton = (Button) findViewById(R.id.button1);

		mToggle = (ToggleButton) findViewById(R.id.toggleButton1);
		mToggle.setOnCheckedChangeListener(this);

		mSpinner = (Spinner) findViewById(R.id.spinner1);
		mSpinner.setAdapter(new ArrayAdapter<String>(this, R.layout.text_view,
				interval));
		mSpinner.setOnItemSelectedListener(this);

		mHandler = new Handler();

	}

	public void onPush(View view) {
		mCount--;
		if (mCount <= 0) {
			mCount = Integer.parseInt(mEdit.getText().toString());
			mSet++;
			mDialog = new ProgressDialog(this);
			mDialog.show();
			mTimer = new Timer();
			mTimerTask = new TimerTask() {

				@Override
				public void run() {
					mHandler.post(new Runnable() {

						@Override
						public void run() {
							if (mDialog != null) {
								mDialog.dismiss();
							}
						}
					});
				}
			};
			mTimer.schedule(mTimerTask, mInterval);
		}
	}

	@Override
	public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
		if (arg1) {
			mEdit.setEnabled(false);
			if (mEdit.getText().toString().length() != 0) {
				mCount = Integer.parseInt(mEdit.getText().toString());
			} else {
				mCount = 10;
				mEdit.setText("10");
			}
			mButton.setEnabled(true);
		} else {
			mButton.setEnabled(false);
			mEdit.setEnabled(true);
		}
	}

	@Override
	public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
			long arg3) {
		mInterval = 30000 * (arg2 + 1);
	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {

	}
}
